import javax.swing.*;
import java.io.File;
import java.util.regex.Pattern;

class SearchWorker extends SwingWorker<Integer, File> {
	Pattern compile;
	File f;
	DefaultListModel<String> model;

	public SearchWorker(File f, String rule, DefaultListModel<String> model) {
		this.f = f;
		try {
			compile = Pattern.compile(rule);
		} catch (Exception e) {
			cancel(true);
		}
		this.model = model;
		model.removeAllElements();
	}

	@Override
	protected Integer doInBackground() throws Exception {
		FileExtractUtil.descendants(f)
				.filter(file -> compile.matcher(file.getAbsolutePath()).find())
				.forEach(this::publish);

		return null;
	}

	@Override
	protected void process(java.util.List<File> chunks) {
		for (File file : chunks) {
			model.addElement(file.getAbsolutePath());
		}
	}
}
